<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增印刷报工单</div>
            <div v-else-if="route.query?.info">
              印刷报工单{{ route.query?.audit ? "审核" : "详情" }}
              <el-tag>{{ form.code }}</el-tag>
            </div>
            <div v-else>编辑印刷报工单</div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
          <div class="flex items-center" v-if="route.query.audit">
            <el-button
              type="primary"
              :loading="auditLoading"
              @click="handleAudit"
              >审 核</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="120px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="报工日期" prop="reportDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.reportDate"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="机台" prop="machineName">
                    <el-input
                      v-model="form.machineName"
                      readonly
                      placeholder="请选择机台"
                      @click="openDialog"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="机长" prop="headName">
                    <el-input
                      v-model="form.headName"
                      readonly
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="上报人" prop="createBy">
                    <el-input
                      v-model="form.createBy"
                      readonly
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="当班日期" prop="dutyDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.dutyDate"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="保养明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">保养明细</span>
          </template>
          <div class="order-form">
            <el-form
              :model="data"
              ref="reportCareListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table :data="data.reportCareList" border>
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="保养单编码"
                  width="300"
                  prop="code"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="时长(h)"
                  width="150"
                  prop="timeLength"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.timeLength"
                      type="number"
                      placeholder="请输入时长(h)"
                    >
                      <template #append>h</template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  width="200"
                  prop="remark"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="请输入内容"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="人员明细" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">人员明细</span>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddReportUserList"
          >
            选择人员
          </el-button>
          <div class="order-form">
            <el-form
              :model="data"
              ref="reportUserListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.reportUserList"
                ref="reportUserListRef"
                border
                :header-cell-class-name="mustPeople"
                :summary-method="getSummaries"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="员工名称"
                  min-width="100"
                  prop="name"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="员工工号"
                  min-width="160"
                  prop="no"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="计件工资(元)"
                  min-width="150"
                  prop="wagesPiece"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                      :rules="[
                        {
                          required: true,
                          message: '计件工资',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @blur="changeWagesSum(scope.row, scope.$index)"
                        v-model="scope.row.wagesPiece"
                        type="number"
                        placeholder="请输入计件工资(元)"
                      >
                        <template #append>元</template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                                    label="补助工资(元)"
                                    min-width="160"
                                    prop="wagesSubsidy"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                           
                                        >
                                            <el-input
                                                @blur="changeWagesSum(scope.row, scope.$index)"
                                                v-model="scope.row.wagesSubsidy"
                                                type="number"
                                                placeholder="请输入补助工资(元)"
                                            >
                                                <template #append>元</template>
                                            </el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <!-- <el-table-column
                                    label="合计工资(元)"
                                    min-width="120"
                                    prop="wagesSum"
                                    align="center"
                                ></el-table-column> -->
                <el-table-column
                  prop="proportion"
                  label="岗位占比"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      type="number"
                      @input="limitInput('proportion', scope.row)"
                      :disabled="flag"
                      v-model="scope.row.proportion"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!flag"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="完成工作量明细" name="4">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">完成工作量明细</span>
            <el-button
              v-if="route.query?.audit"
              style="margin-left: 10px"
              size="small"
              type="danger"
              @click="handleReport"
            >
              质量事故上报
            </el-button>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddPieceList"
          >
            选择生产单
          </el-button>
          <div class="order-form">
            <el-form :model="data" ref="reportWorkListForm" class="data-form">
              <el-table
                :data="data.reportWorkList"
                ref="reportWorkListRef"
                height="600px"
                border
                :header-cell-class-name="mustReport"
                :summary-method="getSummariesWorkList"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="类型"
                  align="center"
                  width="80"
                  prop="type"
                >
                  <template v-slot="{ row }">
                    <el-tag
                      :type="row.type == 1 ? 'success' : ''"
                      effect="dark"
                    >
                      {{ row.type == 1 ? "封面" : "内文" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  label="生产单编码"
                  min-width="150"
                  align="center"
                  prop="produceCode"
                ></el-table-column>
                <el-table-column
                  label="出版编码"
                  min-width="120"
                  prop="pubNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="书刊名称"
                  min-width="240"
                  prop="orderName"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="品种"
                  min-width="160"
                  prop="breed"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="印张"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="sheet"
                ></el-table-column>
                <el-table-column
                  label="贴数"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="labeling"
                ></el-table-column>
                <el-table-column
                  label="印数"
                  align="center"
                  prop="printAmount"
                ></el-table-column>
                <el-table-column
                  label="完成数量"
                  min-width="120"
                  align="center"
                  prop="finishNum"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.finishNum'"
                      :rules="[
                        {
                          required: true,
                          message: '完成数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        :max="scope.row.maxNum"
                        @mousewheel.prevent
                        @blur="changePieceLing(scope.row, scope.$index)"
                        v-model="scope.row.finishNum"
                        type="number"
                        placeholder="请输入完成数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="是否全部报工"
                  align="center"
                  width="100"
                  prop="multipleReport"
                >
                  <template #default="scope">
                    <el-select
                      @blur="changeMultipleReport(scope.row, scope.$index)"
                      :disabled="
                        flag || !allowedMachineIds.includes(form.machineId)
                      "
                      v-model="scope.row.multipleReport"
                    >
                      <el-option value="1" label="是"></el-option>
                      <el-option value="0" label="否"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件令数"
                  align="center"
                  prop="pieceLing"
                ></el-table-column>
                <el-table-column
                  label="计件标准"
                  min-width="120"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="standard"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.standard'"
                      :rules="[
                        {
                          required: true,
                          message: '计件标准',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        @mousewheel.prevent
                        @blur="changeAmount(scope.row, scope.$index)"
                        v-model="scope.row.standard"
                        type="number"
                        placeholder="请输入计件标准"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件金额"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="amount"
                ></el-table-column>
                <el-table-column
                  label="印色"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="printColor"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_print_color"
                      :value="scope.row.printColor"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="换版数量"
                  min-width="120"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="exchangeNum"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.exchangeNum'"
                      :rules="[
                        {
                          required: true,
                          message: '换版数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @mousewheel.prevent
                        :disabled="flag"
                        @blur="changeAmountH(scope.row, scope.$index)"
                        v-model="scope.row.exchangeNum"
                        type="number"
                        placeholder="请输入换版数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件标准(换版)"
                  min-width="120"
                  align="center"
                  prop="standardH"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.standardH'"
                      :rules="[
                        {
                          required: true,
                          message: '计件标准(换版)',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @mousewheel.prevent
                        :disabled="flag"
                        @blur="changeAmountH(scope.row, scope.$index)"
                        v-model="scope.row.standardH"
                        type="number"
                        placeholder="请输入计件标准"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件金额(换版)"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="amountH"
                ></el-table-column>
                <el-table-column
                  label="预计用纸令数"
                  min-width="120"
                  align="center"
                  prop="expectLing"
                >
                </el-table-column>
                <el-table-column
                  label="实际用纸令数"
                  min-width="100"
                  align="center"
                  prop="realityLing"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.realityLing'"
                      :rules="[
                        {
                          required: true,
                          message: '实际用纸令数',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        @blur="changeRealityLing(scope.row, scope.$index)"
                        v-model="scope.row.realityLing"
                        type="number"
                        placeholder="请输入实际用纸令数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="盈亏令数"
                  min-width="120"
                  align="center"
                  prop="ykLing"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'reportWorkList.' + scope.$index + '.ykLing'"
                      :rules="[
                        {
                          required: true,
                          message: '盈亏令数',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.ykLing"
                        type="number"
                        placeholder="请输入盈亏令数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="另行加放"
                  align="center"
                  prop="lxjf"
                ></el-table-column>
                <el-table-column
                  label="累计已上报数量"
                  align="center"
                  prop="totalNum"
                ></el-table-column>
                <el-table-column
                  label="最大允许上报数量"
                  align="center"
                  prop="maxNum"
                ></el-table-column>
                <!-- 印刷数*（1+损耗系数） -->
                <el-table-column
                  label="损耗比例"
                  align="center"
                  prop="lossCoefficient"
                ></el-table-column>
                <el-table-column
                  label="备注"
                  width="150"
                  prop="remark"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      :disabled="flag"
                      v-model="scope.row.remark"
                      placeholder="请输入内容"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="route.query.audit"
                  label="事故原因"
                  width="150"
                  prop="reason"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!route.query.info"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeleteOrder(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="下单日期"
                  min-width="120"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="orderTime"
                >
                  <template v-slot="{ row }">
                    {{ row.orderTime ? row.orderTime.split("T")[0] : "" }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="印刷方式"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="printType"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_package"
                      :value="scope.row.printType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="120"
                  v-if="route.query.audit"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      @click="handleSingleReport(scope.row)"
                    >
                      质量事故上报
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeWorkBenchData"
      :search="{ type: '2' }"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench>
    <userWorkListVue
      :visible="searchPeopleVisible"
      :userWorkList="userWorkList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></userWorkListVue>
    <pieceList
      :visible="pieceListOpen"
      @changeUpdate="changePieceListData"
      :orderSelectList="orderSelectList"
      :params="params"
      @cancel="
        () => {
          pieceListOpen = false;
        }
      "
    ></pieceList>
  </div>
</template>

<script setup>
import {
  addReportList,
  getReportById,
  listReportCare,
  updateStatus,
} from "@/api/production/printReport.js";
import SearchWorkBench from "@/components/SearchWorkBench";
import userWorkListVue from "@/components/userWorkList";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import pieceList from "./pieceList.vue";
import { toNumber } from "@/utils/ruoyi";
import { nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const searchPeopleVisible = ref(false);
const pieceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const orderSelectList = ref([]);
const activeNames = ["1", "2", "3", "4"];
const userRef = ref(null);
const userWorkList = ref([]);
const reportUserListForm = ref(null);
const flag = ref(false);
const auditLoading = ref(false);
const totalWagesSum = ref(0);
const totalAmount = ref(0);
const totalAmountH = ref(0);
const params = ref({});
const num = ref(0);
const reportWorkListForm = ref(null);
const btnLoading = ref(false);
const allowedMachineIds = [
  "e6f5f7d8bd784d738e9d0b2c12b963ae",
  "de30779372a24043967df6f8b0b375f4",
  "b8a5b7fecaaf440e94e7e96d9097ca7b",
];
const data = reactive({
  reportCareList: [], // 保养
  reportUserList: [], // 人员
  reportWorkList: [], // 完成
  form: {
    type: "1",
  },
  rules: {
    machineName: [{ required: true, message: "机台不能为空", trigger: "blur" }],
    reportDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
  },
});
nextTick(() => {
  form.value.createBy = userInfo.name;
});
const { mes_paper_package, ems_order_print_color } = proxy.useDict(
  "mes_paper_package",
  "ems_order_print_color"
);
const { form, rules, reportCareList, reportUserList, reportWorkList } =
  toRefs(data);
if (route.query?.id) {
  getReportById({ id: route.query.id }).then((res) => {
    Object.assign(form.value, { ...res.data });
    params.value = { machineId: res.data.machineId };
    reportCareList.value = res.data.reportCareList;
    reportUserList.value = res.data.reportUserList;
    reportWorkList.value = res.data.reportWorkList;
    if (route.query.info) {
      flag.value = true;
    }
  });
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return toNumber(prev + curr, 2);
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "wagesPiece") {
        totalWagesSum.value = Number(sums[index]);
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
// 合计
const getSummariesWorkList = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["amount", "amountH", "realityLing", "expectLing"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (fieldsToSum.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return toNumber(prev + curr, 4);
          } else {
            return toNumber(prev, 2);
          }
        }, 0)}`;
        if (column.property == "amount") {
          totalAmount.value = toNumber(sums[index], 2);
        }
        if (column.property == "amountH") {
          totalAmountH.value = toNumber(sums[index], 2);
        }
      } else {
        sums[index] = "";
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

//限制只能输入4位小数
function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,1})/g)[0] || "";
  handleTotalCount();
}

const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};

const mustReport = (obj) => {
  //
  let mustColumns = [9, 11, 13, 14, 17, 18];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// 质量上报
const handleReport = () => {
  ElMessageBox.prompt("请输入质量原因", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "请输入质量原因",
  })
    .then(({ value }) => {
      reportWorkList.value.forEach((item) => {
        item.reason = value;
        item.accident = "1";
      });
    })
    .catch(() => {});
};
// 单个上报
const handleSingleReport = (row) => {
  ElMessageBox.prompt("请输入质量原因", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "请输入质量原因",
  })
    .then(({ value }) => {
      row.reason = value;
      row.accident = "1";
      // updateStatus({ pid: row.pid, voidReason: value, status: 0 }).then(res => {
      //     getList()
      //     proxy.$modal.msgSuccess('作废成功')
      // })
    })
    .catch(() => {});
};

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.reportDate = `${year}-${month}-${day} `;
  form.value.dutyDate = `${year}-${month}-${day} `;
};
getCurrentDateTime();
// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选择人员
const handleAddReportUserList = () => {
  peopleSelectList.value = reportUserList.value;
  searchPeopleVisible.value = true;
};
// 选中的机台
const changeWorkBenchData = (row) => {
  reportUserList.value = [];
  reportWorkList.value = [];
  userWorkList.value = row.mesMachineUserList.map((item) => {
    return {
      ...item,
      name: item.mesUsers.name,
      code: item.mesUsers.code,
    };
  });
  form.value.machineName = row.machineName;
  form.value.machineId = row.pid;
  params.value = { machineId: row.pid, type: 2 }; //机台类型type:4
  form.value.headName = row.headUserName;
  listReportCare({ status: 2, machineNo: row.machineNo }).then((res) => {
    reportCareList.value = res.data.map((item) => {
      return {
        code: item.code,
        timeLength: undefined,
        remark: undefined,
      };
    });
  });
  searchVisible.value = false;
};
// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(reportUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      reportUserList.value.push({
        ...item,
        remark: null,
        no: item.code,
        wagesSubsidy: null,
        wagesPiece: null,
      });
      codeSet.add(item.id);
    }
  });
  reportUserList.value = reportUserList.value.filter((item) =>
    row.some((rowItem) => rowItem.id === item.id)
  );
  if (reportWorkList.value.length > 0) {
    handleTotalCount();
  }
  searchPeopleVisible.value = false;
};
// 合计工资
const changeWagesSum = (row, index) => {
  reportUserList.value[index].wagesSum =
    Number(row.wagesPiece) + Number(row.wagesSubsidy);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    reportUserList.value = reportUserList.value.filter(
      (item) => item.id !== row.id
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};
const handleDeleteOrder = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    reportWorkList.value = reportWorkList.value.filter((item) =>
      item.id ? item.id !== row.id : item.pieceId != row.pieceId
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};

// 选择生产单
const handleAddPieceList = () => {
  if (!form.value.machineId) {
    return ElMessage({
      message: "请先选择机台",
      type: "warning",
    });
  }
  orderSelectList.value = reportWorkList.value;
  pieceListOpen.value = true;
};
// 选中的数据
const changePieceListData = (row) => {
  const codeSet = new Set(reportWorkList.value.map((data) => data.pieceId));
  row.forEach((item, index) => {
    if (!codeSet.has(item.pieceId)) {
      reportWorkList.value.push({
        ...item,
        //计件金额=计件令数*计件标准
        amount: toNumber(
          Number(item.pieceLing || 0) * Number(item.standard || 0),
          2
        ),
        tonnageCoefficient: item.tonnageCoefficient, //吨位系数
        fromType: "1",
        bookCode: item.bookNo,
        orderName: item.bookName,
        labeling: item.pieceView,
      });
      codeSet.add(item.pieceId);
    }
  });
  reportWorkList.value.forEach((ele, index) => {
    // changeAmount(ele, index);
    changeAmountH(ele, index);
  });
  pieceListOpen.value = false;
};

const handleTotalCount = () => {
  // 计算计件工资
  const totalLing = reportWorkList.value.reduce((prev, item) => {
    prev += Number(item.amount || 0) + Number(item.amountH || 0);
    return prev;
  }, 0);
  const totalProportion = reportUserList.value.reduce((prev, item) => {
    prev += Number(item.proportion || 0);
    return prev;
  }, 0);
  reportUserList.value.forEach((item) => {
    if (item.proportion) {
      item.wagesPiece = toNumber(
        (Number(item.proportion) / totalProportion) * totalLing,
        2
      );
      // item.wagesSum = toNumber(item.wagesPiece + Number(item.wagesSubsidy || 0), 2)
    }
  });
};
const changeMultipleReport = (row, index) => {
  changePieceLing(row, index);
};
// 计算计件令数
const changePieceLing = (row, index) => {
  if (reportWorkList.value[index].finishNum <= 0) {
    reportWorkList.value[index].finishNum = null;
    return ElMessage({
      message: `完工数量不能小于0`,
      type: "warning",
    });
  }
  //八色（1030）SM1号机 八色（1055）XL1号机  四色（930）1号机  这3个机台不限制最大上报量，令数=完成数量/1000
  if (
    form.value.machineName == "八色（1030）SM1号机" ||
    form.value.machineName == "八色（1055）XL1号机" ||
    form.value.machineName == "四色（930）1号机"
  ) {
    //完成数量不限制
  } else if (Number(row.finishNum) > Number(row.maxNum)) {
    row.finishNum = row.maxNum;
  }
  /** 实际用纸令数   realityLing
    平张：完成数量（计件令数）*印张/1000*（1+损耗系数）
    卷筒：完成数量（计件令数）*印张/1000*（1+损耗系数）/吨位系数
     */
  //   if (row.printType == 1) {
  //     // 平张
  //     row.realityLing = toNumber(
  //       ((Number(row.finishNum || 0) * Number(row.sheet || 0)) / 1000) *
  //         (1 + Number(row.lossCoefficient || 0)),
  //       4
  //     );
  //   } else {
  //     row.realityLing = toNumber(
  //       (((Number(row.finishNum || 0) * Number(row.sheet || 0)) / 1000) *
  //         (1 + Number(row.lossCoefficient || 0))) /
  //         Number(row.tonnageCoefficient || 1),
  //       4
  //     );
  //   }
  /*** 注
     * if (row.printType == 2) {
    row.expectLing = toNumber(
      (Number(row.finishNum || 0) * Number(row.sheet)) / 1000,
      4
    );
  } else {
    row.expectLing = toNumber(Number(row.finishNum || 0) / 1000, 4);
  }
  row.realityLing = row.expectLing;
  row.ykLing = toNumber(row.expectLing - row.realityLing, 4);
     * 
     */
  // if (
  //     Number(reportWorkList.value[index].finishNum) +
  //         Number(reportWorkList.value[index].totalNum) >
  //     Number(reportWorkList.value[index].maxNum)
  // ) {
  //     reportWorkList.value[index].finishNum = undefined
  //     return ElMessage({
  //         message: '完工数量+累计已上报数量不能大于最大允许上报数量',
  //         type: 'warning',
  //     })
  // }

  //计件令数  完成工作量=(印数：printAmount * 印张：sheet*（1+损耗系数：lossCoefficient）+另行加放:lxjf）

  //1、印数大于等于1000，按照 “完成工作量/1000”计算
  //2、印数小于1000，需要判断完成量*0.99>=最大报工量  =1
  //<1按照 “（完成工作量/1000”计算

  //八色（1030）SM1号机 八色（1055）XL1号机  四色（930）1号机  这3个机台不限制最大上报量，令数=完成数量/1000
  if (
    form.value.machineName == "八色（1030）SM1号机" ||
    form.value.machineName == "八色（1055）XL1号机" ||
    form.value.machineName == "四色（930）1号机"
  ) {
    // 2024-6-28 报工明细表增加字段”是否全部报工“，默认否，如果选的是“否”，则计件令数=完成数量/1000，并且这个报工单不减纸的库存，
    if (row.multipleReport == "0") {
      reportWorkList.value[index].pieceLing = toNumber(
        Number(row.finishNum || 0) / 1000,
        4
      );
    } else {
      // 如果选的是“是”，则计件令数=完成数量/1000，如果计件令数<1,默认计件令数=1，并且这个报工单减纸的库存，
      reportWorkList.value[index].pieceLing = toNumber(
        Number(row.finishNum || 0) / 1000,
        4
      );
      if (reportWorkList.value[index].pieceLing < 1) {
        reportWorkList.value[index].pieceLing = 1;
      }
    }
  } else {
    //20240617 令数=完成数量/1000 如果小于1，则等于1
    reportWorkList.value[index].pieceLing = toNumber(
      Number(row.finishNum || 0) / 1000,
      4
    );
    // reportWorkList.value[index].pieceLing = toNumber(1 - num / 1000, 4);
    if (reportWorkList.value[index].pieceLing < 1) {
      //卷筒 计件令数小于1，则等于1
      reportWorkList.value[index].pieceLing = 1;
    }
    // //0609 修改
    // if (row.printType == 1) {
    //   //完成数量1 =（ 印数*印张*（1+损耗系数）+另行加放）
    //   //平张 （ 印数*印张*（1+损耗系数）+另行加放）小于1000 并且  （累计上报量（totalNum）+完成数量）大于等于 0.99*印数*印张：令数=1-（完成数量1-本次最大上报量）/1000
    //   row.JSCount = Math.ceil(
    //     Number(row.printAmount || 0) *
    //       Number(row.sheet || 0) *
    //       (1 + Number(row.lossCoefficient || 0)) +
    //       Number(row.lxjf || 0)
    //   );
    //   row.BJCount = Number(row.printAmount || 0) * Number(row.sheet || 0);
    // } else {
    //   //完成数量1 =（ 印数*（1+损耗系数）+另行加放）
    //   //卷筒 【印数*（1+损耗系数）+另行加放】小于1000 并且 （累计上报量（totalNum）+完成数量）大于等于 0.99*印数：令数=1-（完成数量1-本次最大上报量）/1000）
    //   row.JSCount = Math.ceil(
    //     Number(row.printAmount || 0) * (1 + Number(row.lossCoefficient || 0)) +
    //       Number(row.lxjf || 0)
    //   );
    //   row.BJCount = Number(row.printAmount || 0);
    // }
    // if (
    //   Number(row.JSCount || 0) < 1000 &&
    //   Number(row.totalNum || 0) + Number(row.finishNum || 0) >=
    //     0.99 * row.BJCount
    // ) {
    //   // reportWorkList.value[index].pieceLing =1;
    //   num = Number(row.JSCount || 0) - Number(row.maxNum || 0);
    //   num = num < 0 ? 0 : num;
    //   reportWorkList.value[index].pieceLing = toNumber(1 - num / 1000, 4);
    //   if (row.printType == 2 && reportWorkList.value[index].pieceLing < 1) {
    //     //卷筒 计件令数小于1，则等于1
    //     reportWorkList.value[index].pieceLing = 1;
    //   }
    // } else {
    //   // if(Number(row.printAmount || 0)>=1000)
    //   // 完工数量/1000
    //   reportWorkList.value[index].pieceLing = toNumber(
    //     Number(row.finishNum || 0) / 1000,
    //     4
    //   );
    // }
  }

  //计件金额=计件令数*计件标准
  reportWorkList.value[index].amount = toNumber(
    Number(row.pieceLing || 0) * Number(row.standard || 0),
    2
  );
  // if (row.printType == 1) {
  //   reportWorkList.value[index].amount = toNumber(
  //     (Number(reportWorkList.value[index].pieceLing || 0) < 1
  //       ? 1
  //       : Number(reportWorkList.value[index].pieceLing)) *
  //       Number(row.standard || 0),
  //     2
  //   );
  // } else {
  //   // 卷筒 再*印张
  //   reportWorkList.value[index].amount = toNumber(
  //     (Number(reportWorkList.value[index].pieceLing || 0) < 1
  //       ? 1
  //       : Number(reportWorkList.value[index].pieceLing)) *
  //       Number(row.standard || 0) *
  //       Number(row.sheet || 0),
  //     2
  //   );
  // }

  // changeAmount()
  handleTotalCount();
};
//  计算计件金额
const changeAmount = (row, index) => {
  // 计件令数*计件标准
  if (row.printType == 1) {
    reportWorkList.value[index].amount = toNumber(
      (Number(reportWorkList.value[index].pieceLing || 0) < 1
        ? 1
        : Number(reportWorkList.value[index].pieceLing)) *
        Number(row.standard || 0),
      2
    );
  } else {
    // 卷筒 再*印张
    reportWorkList.value[index].amount = toNumber(
      (Number(reportWorkList.value[index].pieceLing || 0) < 1
        ? 1
        : Number(reportWorkList.value[index].pieceLing)) *
        Number(row.standard || 0) *
        Number(row.sheet || 0),
      2
    );
  }

  handleTotalCount();
};
//  计算计件金额（换版）
const changeAmountH = (row, index) => {
  // 换版数量*计件标准（换版）
  reportWorkList.value[index].amountH = toNumber(
    Number(row.exchangeNum || 0) * Number(row.standardH || 0),
    2
  );
  handleTotalCount();
};
const changeRealityLing = (row, index) => {
  // 盈亏 预计-实际
  reportWorkList.value[index].ykLing = toNumber(
    Number(row.expectLing || 0) - Number(row.realityLing || 0),
    4
  );
};
//  返回
const goBack = () => {
  // router.replace({ path: "/production/printReport" }); ///production/printReport
  tagsViewStore.delView(route);
  router.go(-1);
};

// const goBack = () => {
//   // tagsViewStore.delView(route);
//   if (!route.query?.id) {
//     router.push({
//       path: "/production/printReport",
//       query: {
//         caches: 1,
//       },
//     });
//   } else if (route.query?.info) {
//     router.push({
//       path: "/production/printReport",
//     });
//     // tagsViewStore.delView(route);
//     // router.go(-1);
//   } else if (!route.query?.info) {
//     router.push({
//       path: "/production/printReport",
//       query: {
//         caches: 1,
//       },
//     });
//     // tagsViewStore.delView(route);
//     // router.go(-1);
//   }
// };

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 保存
const submitForm = async () => {
  btnLoading.value = true;
  // debugger;
  try {
    await userRef.value.validate();
    await reportUserListForm.value.validate();
    await reportWorkListForm.value.validate();

    if (reportWorkList.value.length > 0) {
      const invalidItem = reportWorkList.value.findIndex(
        (item) =>
          item.finishNum <= 0 ||
          item.exchangeNum <= 0 ||
          item.standardH <= 0 ||
          item.standard <= 0 ||
          item.realityLing <= 0
      );

      if (invalidItem !== -1) {
        btnLoading.value = false;
        return ElMessage({
          message: `第${
            invalidItem + 1
          }行的完成数量、换版数量、计件标准(换版)、计件标准、实际用纸令数不能小于等于0`,
          type: "warning",
        });
      }
    }

    if (reportUserList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写人员明细`,
        type: "warning",
      });
    }

    if (reportWorkList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: `请填写完成工作量明细`,
        type: "warning",
      });
    }
    if (
      toNumber(Number(totalWagesSum.value), 2) !=
      toNumber(Number(totalAmount.value) + Number(totalAmountH.value), 2)
      //Number(totalAmount.value) + Number(totalAmountH.value)
    ) {
      btnLoading.value = false;
      return ElMessage({
        message: "合计工资与计件金额不符",
        type: "warning",
      });
    }
    clearId(reportUserList.value, "id");
    if (route.query?.id) {
      clearId(reportCareList.value, "id");
      clearId(reportWorkList.value, "id");
      await addReportList({
        ...form.value,
        reportCareList: reportCareList.value,
        reportUserList: reportUserList.value,
        reportWorkList: reportWorkList.value,
      });
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      goBack();
    } else {
      // 新增
      form.value.status = 0; //0:未审核 1：已审核  2：审核未通过
      await addReportList({
        ...form.value,
        reportCareList: reportCareList.value,
        reportUserList: reportUserList.value,
        reportWorkList: reportWorkList.value,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    btnLoading.value = false;
    if (Object.keys(error)?.join(",").includes(".")) {
      const errInfoList = Object.values(error);
      const err = [];
      errInfoList.forEach((item) => {
        err.push(item[0].message);
      });
      ElMessage({
        message: `请将${err.join("、")}信息补充完整`,
        type: "warning",
      });
    }
  }
};

// 审核
const handleAudit = () => {
  auditLoading.value = true;
  clearId(reportCareList.value, "id");
  clearId(reportWorkList.value, "id");
  //0613 更改
  updateStatus({ status: 1, id: form.value.id })
    .then((res) => {
      ElMessage({
        message: "审核成功",
        type: "success",
      });
      goBack();
    })
    .catch((err) => {
      auditLoading.value = false;
    });
  // addReportList({
  //   ...form.value,
  //   reportCareList: reportCareList.value,
  //   reportUserList: reportUserList.value,
  //   reportWorkList: reportWorkList.value,
  // }).then((res) => {
  //   updateStatus({ status: 1, id: form.value.id }).then((res) => {
  //     ElMessage({
  //       message: "审核成功",
  //       type: "success",
  //     });
  //     goBack();
  //   });
  // });
};
</script>

<style lang="scss" scoped>
.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}
</style>
